<script setup lang='ts'>
import type { IQueryCompane, ISelectOpenData } from '@fl/api/bidding-api/model/bidding'
import type { VxePagerEvents } from 'vxe-table'

import breadCrumb from '@/components/bread-crumb.vue'
import { FlowCatchOption } from '@/constants'
import { Message } from '@element-plus/icons-vue'
import { useGetEnterpriseInfo, useSelectOpenRaceAnnouncementVoList } from '@fl/api/bidding-api'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep, isEqual, throttle } from 'lodash-es'
import { ref } from 'vue'

import Footer from '../footer/footer.vue'

import tenderBg from '/assets/home/tender-bg.png'

const { query } = useRoute()
const { push } = useRouter()

const defaultState = {
    announcementType: Number(query.second ?? 1),
}
// 公告状态
const state = ref<ISelectOpenData>(cloneDeep(defaultState))
// 查询的状态
const queryState = ref<ISelectOpenData>(cloneDeep(defaultState))
const records = ref()
const tableRef = ref()

const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

const page = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))

const asideData = [
    {
        children: [
            {
                label: '招标公告',
                name: '1-1',
                value: 1,

            },
            {
                label: '中标公告',
                name: '1-2',
                value: 2,
            },
            {
                label: '变更公告',
                name: '1-3',
                value: 4,
            },
            {
                label: '其他公告',
                name: '1-3',
                value: 3,
            },
        ],
        label: '招采信息',
        name: '1',
        value: 0,
    },
]
// type IQueryEnterprise = {
//     enterprise: IQueryCompane
//     loading: boolean
//     page: IPage
// }
const requestEnterprise = ref<IQueryCompane>({
    enterpriseName: '',
})
const pageEnterprise = ref({
    pageNum: 1,
    pageSize: 100000,
})
const { data: enterPrise, isLoading: isLoadingEnterprise, refetch: _ } = useGetEnterpriseInfo(pageEnterprise, requestEnterprise)
const enterpriseOptions = computed(() => {
    console.log('enterPrise', enterPrise)
    if (enterPrise.value && enterPrise.value.code === 200) {
        return enterPrise.value.rows
    }
    else {
        return []
    }
})
function enterQuery(query) {
    requestEnterprise.value.enterpriseName = query
}

const colspan = 8
const columns = ref([
    {
        colProps: {
            span: colspan,
        },
        label: '公告标题',
        prop: 'title',
    },
    {
        colProps: {
            span: colspan,
        },
        hidden: false,
        hideInForm: computed(() => state.value.announcementType !== 2),
        label: '中标单位名称',
        prop: 'winningCompanyName',
    },

    {
        colProps: {
            span: colspan,
        },
        hidden: false,
        hideInForm: computed(() => state.value.announcementType === 3 || state.value.announcementType === 4),
        label: '招标方式',
        options: [
            {
                label: '公开竞选',
                value: '2',
            },
            {
                label: '邀请选用',
                value: '1',
            },
        ],
        prop: 'procureType',
        valueType: 'select',

    },

    {
        colProps: {
            span: colspan,
        },
        hidden: false,
        hideInForm: computed(() => state.value.announcementType !== 1),
        label: '公告状态',
        options: [
            {
                label: '正在报名',
                value: 1,
            },
            {
                label: '报名结束',
                value: 2,
            },
            {
                label: '已终止',
                value: 3,
            },
            {
                label: '已流标',
                value: 4,
            },
            {
                label: '已废标',
                value: 5,
            },
        ],
        prop: 'applicationStatus',
        valueType: 'select',

    },
    {
        colProps: {
            span: colspan,
        },
        hidden: false,
        hideInForm: computed(() => state.value.announcementType !== 4),
        label: '变更类型',
        options: [
            {
                label: '终止',
                value: '1',
            },
            {
                label: '流标',
                value: '2',
            },
            {
                label: '废标',
                value: '3',
            },
            {
                label: '延期',
                value: '4',
            },
        ],
        prop: 'abnormalProcess',
        valueType: 'select',

    },
    {
        colProps: {
            span: colspan,
        },
        label: '所属公司',
        prop: 'supplierId',
    },
    {
        colProps: {
            span: colspan * 2,
        },
        fieldProps: {
            'endPlaceholder': '请选择结束时间',
            'placeholder': '请选择报名截止时间',
            'rangeSeparator': '-',
            'startPlaceholder': '请选择开始时间',
            'type': 'datetimerange',
            'value-format': 'YYYY-MM-DD HH:mm:ss',
        },
        hidden: false,
        hideInForm: computed(() => state.value.announcementType !== 1),
        label: '报名截止时间',
        prop: 'applicationEndTime',
        valueType: 'date-picker',
    },

    {
        colProps: {
            span: colspan * 2,
        },
        fieldProps: {
            'endPlaceholder': '请选择结束时间',
            'placeholder': '请选择发布时间',
            'rangeSeparator': '-',
            'startPlaceholder': '请选择开始时间',
            'type': 'datetimerange',
            'value-format': 'YYYY-MM-DD HH:mm:ss',
        },
        label: '发布时间',
        prop: 'createTime',
        valueType: 'date-picker',
    },

])

const { data, refetch } = useSelectOpenRaceAnnouncementVoList(page, queryState)

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.rows)
        tablePage.value.total = Number(data.value.total ?? 0)
    }
})

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}
const _options = {
    columns: [
        { slots: { default: 'publishedTime' }, title: '发布时间', width: '170px' },
        { field: 'title', title: '公告标题' },
        { field: 'company', title: '所属公司' },
    ],
    height: 650,
}
const gridOptions = computed(() => {
    const optional = cloneDeep(_options)
    const announcementType = state.value.announcementType
    if (announcementType === 1) {
        optional.columns.push({ slots: { default: 'operate' }, title: '公告状态', width: '100px' })
        optional.columns.splice(1, 0, { slots: { default: 'applicationEndTime' }, title: '报名截止时间', width: '170px' })
    }
    else if (announcementType === 2) {
        optional.columns.push({ field: 'winningBidder', title: '中标单位' })
    }
    else if (announcementType === 4) {
        optional.columns.push({ slots: { default: 'abnormalProcess' }, title: '变更类型', width: '100px' })
    }
    return optional
})
function reset() {
    state.value = { ...defaultState, announcementType: queryState.value.announcementType }
    queryState.value = { ...state.value }
}
function submit() {
    console.log(state.value)

    if (isEqual(queryState.value, state.value)) {
        refetch()
        return
    }
    if (state.value.applicationEndTime && state.value.applicationEndTime.length > 0) {
        state.value.applicationEndTimeStart = state.value.applicationEndTime[0]
        state.value.applicationEndTimeEnd = state.value.applicationEndTime[1]
    }
    else {
        state.value.applicationEndTimeStart = ''
        state.value.applicationEndTimeEnd = ''
    }
    if (state.value.createTime && state.value.createTime.length > 0) {
        state.value.createTimeStart = state.value.createTime[0]
        state.value.createTimeEnd = state.value.createTime[1]
    }
    else {
        state.value.createTimeStart = ''
        state.value.createTimeEnd = ''
    }
    tablePage.value.currentPage = 1
    queryState.value = { ...state.value }
}
function toApply({ row }) {
    const { announcementId, biddingId } = row
    push({ path: '/apply', query: {
        announcementId,
        biddingId,
    } })
}

function menuItemClick(cItem) {
    state.value.announcementType = cItem.value
    queryState.value.announcementType = cItem.value
    reset()
}
</script>

<template>
    <div>
        <div class="mb-20 h-221">
            <el-image class="h-[100%] w-[100%]"
                      :src="tenderBg"
            />
        </div>

        <el-container class="layout-container-demo pl-[10%] pr-[10%]">
            <el-aside width="200px "
                      class="ml-20 mr-20"
            >
                <el-scrollbar>
                    <el-menu :default-active="(state.announcementType || 1).toString()"
                             :default-openeds="['1']"
                    >
                        <el-sub-menu v-for="item in asideData"
                                     :key="item.name"
                                     :index="item.name"
                        >
                            <template #title>
                                <el-icon><Message /></el-icon>{{ item.label }}
                            </template>

                            <el-menu-item-group>
                                <el-menu-item v-for="(cItem) in item.children"
                                              :key="cItem.name"
                                              :index="cItem.name"
                                              :class="{
                                                  active: state.announcementType === cItem.value,
                                              }"
                                              @click="menuItemClick(cItem)"
                                >
                                    {{ cItem.label }}
                                </el-menu-item>
                            </el-menu-item-group>
                        </el-sub-menu>
                    </el-menu>
                </el-scrollbar>
            </el-aside>

            <el-container class="flex flex-col">
                <breadCrumb />

                <el-header class="h-auto"
                           style="height: auto;"
                >
                    <div class="mb-20">
                        <ElCard shadow="never">
                            <SearchForm v-model="state"
                                        :columns="columns"
                                        submit-text="查询"
                                        @submit="submit"
                                        @reset="reset"
                            >
                                <template #plus-field-supplierId>
                                    <el-select v-model="state.supplierId"
                                               clearable
                                               filterable
                                               :reserve-keyword="false"
                                               placeholder="请输入公司名称"
                                               :loading="isLoadingEnterprise"
                                               @clear="enterQuery('')"
                                               @focus="enterQuery('')"
                                    >
                                        <el-option v-for="item in enterpriseOptions"
                                                   :key="item.supplierId"
                                                   :label="item.enterpriseName"
                                                   :value="item.supplierId"
                                        />
                                    </el-select>
                                </template>
                            </SearchForm>
                        </ElCard>
                    </div>
                </el-header>

                <el-main>
                    <ElCard shadow="never">
                        <SearchTable ref="tableRef"
                                     v-bind="gridOptions"
                                     v-model:pager="tablePage"
                                     :data="records"
                                     @cell-click="toApply"
                                     @page-change="handlePageChange"
                        >
                            <template #publishedTime="{ row }">
                                {{ row.publishedTime ?? '-' }}
                            </template>

                            <template #applicationEndTime="{ row }">
                                {{ row.applicationEndTime ?? '-' }}
                            </template>

                            <template #abnormalProcess="{ row }">
                                {{ FlowCatchOption[row.abnormalProcess] }}
                            </template>

                            <template #operate="{ row }">
                                <el-link v-if="row.abnormalProcess !== null"
                                         :underline="false"
                                         type="warning"
                                >
                                    已{{ FlowCatchOption[row.abnormalProcess] }}
                                </el-link>

                                <el-link v-else-if="row.status === '正在报名'"
                                         :underline="false"
                                         type="success"
                                >
                                    {{ row.status }}
                                </el-link>

                                <el-link v-else-if="row.status === '报名结束'"
                                         :underline="false"
                                         type="warning"
                                >
                                    {{ row.status }}
                                </el-link>
                            </template>
                        </SearchTable>
                    </ElCard>
                </el-main>
            </el-container>
        </el-container>

        <Footer />
    </div>
</template>

<style lang="scss" scoped>
.el-menu-item.active {
    background-color: var(--el-menu-hover-bg-color);
}

:deep(.el-main .el-card .el-card__body) {
    // padding: 0 !important;
}
</style>
